package util;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.io.InputStream;
import java.util.Properties;

public class MongoUtil2 {
    private static MongoClient client = null;
    private static Properties prop = new Properties();
    static {
        //1.获得properties配置文件的路径
        InputStream in = null;
        try {
            in = MongoUtil2.class.getResourceAsStream("/mongo.properties");
            prop.load(in);
        } catch (Exception e) {
            throw new RuntimeException("Mongo配置文件加载失败", e);
        }
        client = new MongoClient(prop.getProperty("host"),Integer.parseInt(prop.getProperty("port")));
    }
    //获得database
    public static MongoDatabase getDB(){
        MongoDatabase db = client.getDatabase(prop.getProperty("database"));
        return db;
    }
    //获得collection
    public static MongoCollection<Document> getCollection(String collectionName){
        MongoDatabase db = getDB();
        MongoCollection<Document> collection = db.getCollection(collectionName);
        return collection;
    }
}
